package com.dianxin.smartpark.service.app.impl;

import cn.hutool.core.util.StrUtil;
import com.chinatelecom.response.common.CommonResponseBody;
import com.chinatelecom.response.constant.ErrMsgEnum;
import com.chinatelecom.response.utils.BeanUtil;
import com.chinatelecom.response.utils.ResponseBodyWrapperUtil;
import com.chinatelecom.response.utils.StringUtils;
import com.dianxin.acl.api.dic.DataDicRpcService;
import com.dianxin.acl.api.dto.SsoUserDTO;
import com.dianxin.smartpark.dao.dataobject.app.SmartParkApp;
import com.dianxin.smartpark.dao.dataobject.app.SmartParkAppExample;
import com.dianxin.smartpark.dao.mapper.app.SmartParkAppMapper;
import com.dianxin.smartpark.dao.qo.app.SmartParkAppQO;
import com.dianxin.smartpark.service.app.SmartParkAppService;
import com.dianxin.smartpark.service.config.FileUrlConfig;
import com.dianxin.smartpark.service.vo.app.SmartParkAppVO;
import com.dianxin.sso.client.context.UserHolderContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @description :
 * @Authort Ricartc
 */

@Service
public class SmartParkAppServiceImpl implements SmartParkAppService {
    public static final Logger logger = LoggerFactory.getLogger(SmartParkAppServiceImpl.class);

    @Resource
    private SmartParkAppMapper smartParkAppMapper;

    @Resource
    private DataDicRpcService dataDicRpcService;

    @Resource
    private FileUrlConfig fileUrlConfig;

    @Override
    public CommonResponseBody<List<SmartParkAppVO>> getApps(SmartParkAppQO qo){
        SmartParkAppExample example = new SmartParkAppExample();
        SmartParkAppExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(qo.getTenantId())){
            criteria.andTenantIdEqualTo(qo.getTenantId());
        }
        if (!StringUtils.isEmpty(qo.getOrgCode())){
            criteria.andOrgCodeEqualTo(qo.getOrgCode());
        }
        if (!StringUtils.isEmpty(qo.getAppId())){
            criteria.andAppIdEqualTo(qo.getAppId());
        }
        //根据平台类型查询
        if (!StringUtils.isEmpty(qo.getPlatformType())){
            criteria.andPlatformTypeEqualTo(qo.getPlatformType());
        }
        //根据应用类型查询
        if(!StringUtils.isEmpty(qo.getAppType())){
            criteria.andAppTypeEqualTo(qo.getAppType());
        }
        //根据应用类型版本名称查询
        if(!StringUtils.isEmpty(qo.getAppVersionName())){
            criteria.andAppVersionNameLike("%"+qo.getAppVersionName()+"%");
        }
        //根据应用类型版本号查询
        if (qo.getAppVersionCode() != null){
            criteria.andAppVersionCodeEqualTo(qo.getAppVersionCode());
        }
        criteria.andIsDeletedEqualTo(0);
        if(qo.getNeedPage()){
            example.setOrderByClause("gmt_create desc limit " + (qo.getPageIndex() - 1) * qo.getPageSize() + "," + qo.getPageSize());
        }else {
            example.setOrderByClause("gmt_create desc limit ");
        }
        List<SmartParkApp> smartParkApps = smartParkAppMapper.selectByExample(example);
        long count = smartParkAppMapper.countByExample(example);
        return ResponseBodyWrapperUtil.successListWrapper(smartParkApps, count, qo, SmartParkAppVO.class);
    }

    @Override
    public CommonResponseBody<SmartParkAppVO> getAppDeatil(SmartParkAppVO vo){
        SmartParkAppExample example = new SmartParkAppExample();
        SmartParkAppExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNull(vo.getId()) || StringUtils.isAnyBlank(vo.getTenantId(),vo.getAppId(),vo.getOrgCode())){
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_PARAME);
        }
        criteria.andIdEqualTo(vo.getId());
        criteria.andTenantIdEqualTo(vo.getTenantId());
        criteria.andAppIdEqualTo(vo.getAppId());
        criteria.andOrgCodeEqualTo(vo.getOrgCode());
        SmartParkApp smartParkApp = smartParkAppMapper.selectByExample(example).get(0);
        try {
            BeanUtil.conversion(smartParkApp,vo);
        } catch (Exception e) {
            logger.error("",e);
        }
        return ResponseBodyWrapperUtil.successWrapper(vo);
    }

    @Override
    public CommonResponseBody<Boolean> saveApp(SmartParkAppVO vo){
        SmartParkApp smartParkApp = new SmartParkApp();
        try {
            BeanUtil.insertConversion(vo,smartParkApp);
        } catch (Exception e) {
            logger.error("",e);
        }
        //雪花算法生成主键ID
//        Long appId = IdUtil.createSnowflake(RandomUtil.randomLong(1, 30), RandomUtil.randomLong(1, 30)).nextId();
//        smartParkApp.setId(appId);
        smartParkApp.beforeInsert();
        smartParkApp.setGmtModified(new Date());
        //将应用文件上传的地址替换为下载地址
        smartParkApp.setFileUrl(fileUrlConfig.getDownloadUrl() + smartParkApp.getFileUrl());
        SsoUserDTO user = UserHolderContext.getUser();
        if (user != null) {
            smartParkApp.setCreator(user.getUserId()+"");
            smartParkApp.setModifier(user.getUserId()+"");
        }
        return ResponseBodyWrapperUtil.toResData(smartParkAppMapper.insertSelective(smartParkApp));
    }

    @Override
    public CommonResponseBody<Boolean> updateApp(SmartParkAppVO vo){
        SmartParkApp smartParkApp = new SmartParkApp();
        try {
            BeanUtil.updateConversion(vo,smartParkApp);
        } catch (Exception e) {
            logger.error("",e);
        }
        //将应用文件上传的地址替换为下载地址
        smartParkApp.setFileUrl(fileUrlConfig.getDownloadUrl() + smartParkApp.getFileUrl());
        smartParkApp.beforeUpdate();
        SsoUserDTO user = UserHolderContext.getUser();
        if (user != null) {
            smartParkApp.setModifier(user.getUserId()+"");
        }
        return ResponseBodyWrapperUtil.toResData(smartParkAppMapper.updateByPrimaryKeySelective(smartParkApp));
    }

    @Override
    public CommonResponseBody<Boolean> deleteApp(SmartParkAppVO vos){
        if (!CollectionUtils.isEmpty(vos.getApps())){
            for (SmartParkAppVO vo : vos.getApps()) {
                 delApps(vo);
            }
            return ResponseBodyWrapperUtil.success();
        }else {
            return delApps(vos);
        }

    }

    private CommonResponseBody<Boolean> delApps(SmartParkAppVO vos) {
        if(StringUtils.isNull(vos.getId())){
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_PARAME);
        }
        SmartParkApp smartParkApp = new SmartParkApp();
        try {
            BeanUtil.updateConversion(vos,smartParkApp);
        } catch (Exception e) {
            logger.error("",e);
        }
        SsoUserDTO user = UserHolderContext.getUser();
        if (user != null) {
            smartParkApp.setModifier(user.getUserId()+"");
        }
        smartParkApp.beforeDelete();
        smartParkAppMapper.updateByPrimaryKeySelective(smartParkApp);
        return ResponseBodyWrapperUtil.success();
    }

    @Override
    public CommonResponseBody<SmartParkAppVO> getCurrentInfoByVersionCode(SmartParkAppVO vo){
        if (StringUtils.isAnyBlank(vo.getTenantId(),vo.getAppType())){
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_PARAME);
        }
        SmartParkAppExample example = new SmartParkAppExample();
        SmartParkAppExample.Criteria criteria = example.createCriteria();
        criteria.andTenantIdEqualTo(vo.getTenantId());
        if(StringUtils.isNotEmpty(vo.getOrgCode())){
            criteria.andOrgCodeEqualTo(vo.getOrgCode());
        }
        if(StringUtils.isNotEmpty(vo.getAppId())){
            criteria.andAppIdEqualTo(vo.getAppId());
        }
        criteria.andAppTypeEqualTo(vo.getAppType());
        example.setOrderByClause("app_version_code desc");
        List<SmartParkApp> smartParkAppS = smartParkAppMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(smartParkAppS)){
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.APP_NOT_EXIT);
        }
        SmartParkAppVO finalVO = new SmartParkAppVO();
        try {
            BeanUtil.conversion(smartParkAppS.get(0),finalVO);
        } catch (Exception e) {
            logger.error("",e);
        }
        return ResponseBodyWrapperUtil.successWrapper(finalVO);
    }

}
